package com.demo.las.controller;

import com.demo.las.dto.ApiResponse;
import com.demo.las.entity.LabReport;
import com.demo.las.service.LabReportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.time.LocalDate;
import org.springframework.format.annotation.DateTimeFormat;

@RestController
@RequestMapping("/api/lab-reports")
@CrossOrigin(origins = "*")
public class LabReportController {

    @Autowired
    private LabReportService labReportService;

    @PostMapping("/upload")
    public ApiResponse<LabReport> upload(@RequestParam("studentName") String studentName,
                                         @RequestParam("studentNo") String studentNo,
                                         @RequestParam("className") String className,
                                         @RequestParam("courseName") String courseName,
                                         @RequestParam(value = "submitDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate submitDate,
                                         @RequestParam("file") MultipartFile file) {
        try {
            LabReport saved = labReportService.saveUpload(studentName, studentNo, className, courseName, submitDate, file);
            return ApiResponse.success("上传成功", saved);
        } catch (IllegalArgumentException e) {
            return ApiResponse.error(400, e.getMessage());
        } catch (IOException e) {
            return ApiResponse.error(500, "服务器保存文件失败: " + e.getMessage());
        }
    }

    @GetMapping
    public ApiResponse<List<LabReport>> list(@RequestParam(value = "studentName", required = false) String studentName,
                                             @RequestParam(value = "studentNo", required = false) String studentNo,
                                             @RequestParam(value = "className", required = false) String className,
                                             @RequestParam(value = "courseName", required = false) String courseName,
                                             @RequestParam(value = "submitDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate submitDate) {
        List<LabReport> reports = labReportService.search(studentName, studentNo, className, courseName, submitDate);
        return ApiResponse.success(reports);
    }
}